<template>
  <div class="routing-wrapper">
    <cfg-toolbar style="marginBottom: 8px;">
      <Icon type="md-apps" style="font-size: 26px; margin-left: 16px;" @click.native="menuShow=!menuShow" />
      <Card v-if="menuShow" class="routingTablewp">
        <routingModel @handleDbClick="getRouting" />
      </Card>
      <h4 v-if="rootData.className" style="margin-left: 10px;">
        {{ `${lang.position}:${rootData.className}` }}
      </h4>
      <Button type="primary" icon="md-checkmark" style="margin-left: 30px;" @click="saveRouting">{{lang.save}}</Button>
      <Button @click="showHier" class="ivu-ml">查看Hier</Button>
    </cfg-toolbar>
    <routingConfigPanel
      :drawer="configDrawer"
      :curIndex="curIndex"
      :hierObject="hierObject"
      :properties="properties"
      @ok="panelConfirm"
      @cancel="panelCancel"
    />
    <div ref="routing" class="routingConfig-wrapper"></div>
  </div>
</template>

<script>
import * as dhx from 'public/3thComponents/diagram/codebase/diagramWithEditor.js';
import 'public/3thComponents/diagram/codebase/diagramWithEditor.css';
import routingConfigPanel from './routingConfigPanel.vue';
import routingModel from './modelDefinition/index';
import routingHierModel from 'public/model/model/hier/routingModel'
import mockData from './data'

const idName = 'nodeId';
export default {
  name: "RoutingConfig",
  data(){
    return {
      menuShow: true,
      classObject: null,
      hierObject: new routingHierModel(),
      configDrawer: {
        show: false
      },
      editor:null,//diagram的编辑器
      diagram:null,//diagram实例
      currentShape:null,
      rootData: {},
      properties: {},
      curIndex: -1,
      curCopyData: {},
    }
  },
  beforeMount() {
    this.classObject=this.$modelObject.create('routingModel')
  },
  mounted() {
    this.init();
    setTimeout(() => {
      // this.getRouting({ type: 'routing', className: 'T12' }, false)
    }, 1000);
  },
  methods:{
    //#region 节点属性弹窗
    showProp(id) {
      let shape=this.diagram.data.getItem(id);
      this.curIndex = this.hierObject.findIndex(idName, id);
      this.properties = shape.properties || {}
      console.log("file: RoutingConfig.vue:66  showProp  id:", id,this.curIndex,this.hierObject)

      this.configDrawer.show=true;
    },
    panelConfirm(properties){
      let hierItem = this.hierObject.hierProperties.content[this.curIndex]
      let shape=this.diagram.data.getItem(hierItem[idName]);

      if (shape && shape.properties) {
        shape.properties = properties
      }
      this.diagram.paint();
      this.configDrawer.show=false;
    },
    panelCancel(){
      this.configDrawer.show=false;
    },
    //#endregion
    // 查询根节点和全部子节点
    getRouting(data, init=true){
      this.menuShow = false
      let filter=`type='${data.type}' && className='${data.className}'`
      this.classObject.query(filter).then(flag=>{
        if(flag){
          // this.classObject.record = mockData.data[0]
          this.hierObject.set(this.classObject.record)
          this.rootData = {...this.classObject.record, [idName]: this.hierObject.rootId }
          this.diagram.data.parse(this.hierObject.web.data)
        }
      })
    },
    saveRouting(){
      this.classObject.record = {
        ...this.classObject.record,
        hierProperties: this.hierObject.hierProperties,
        web: {
          data: this.diagram.data.serialize()
        }
      }
      // this._correctParent();
      this.classObject.updateHierProperties().then(flag=>{
        if(flag){
          this.diagram.paint();
        }
      })
    },
    _addWC(shape){
      let fromId = this.curCopyData.id;
      let newItem = this.addChild(shape, fromId)
      fromId && (this.diagram.data.add(
        { type: "line", from: fromId, to: newItem[idName],
          "fromSide": "right",  "toSide": "left", "added": true,
          connectType: "elbow", forwardArrow: "filled"
        }
      ))
      shape.properties= {};
    },
    _removeWC(shape){
      this.hierObject.delete(idName, shape)
      this.hierObject.hierProperties.content.forEach(item=>{
        if((item.nodeType !=='root') && item.prev.includes(shape.id)){
          item.prev=item.prev.filter(k=>k!==shape.id);
          // let shapeItem=this.diagram.data.getItem(item.id);
          // shapeItem.properties=item;
        }
      })
    },
    _addLine(line){
      if (!line.to || !line.from) {
        return
      }
      /**连接线终点为root，则为非法*/
      if(line.to===this.rootData[idName]){
        this.diagram.data.remove([line.id]);
        return;
      }
      line['forwardArrow'] = 'filled';
      line['added']=true;

      let prev=line.from;
      let id=line.to;
      let curItem=this.hierObject.find(idName, id);
      if (!curItem) {
        this.diagram.data.remove([line.id]);
        return
      }
      let shape=this.diagram.data.getItem(id);

      if(!curItem.prev.includes(prev)){
        curItem.prev.push(prev);
        this.updateChild(curItem)
        // shape.properties=curItem;
      }
      else{
        this.diagram.data.remove([line.id]);
      }
    },
    _removeLine(line){
      let id=line.to;
      let curItem=this.hierObject.find(idName, id);
      if (!curItem) {
        return
      }
      let shape=this.diagram.data.getItem(id);

      curItem.prev=curItem.prev.filter(k=>k!==line.from);
      this.updateChild(curItem)
      // shape.properties=curItem;
    },
    _correctParent(){
      let data=this.diagram.data.serialize();
      this.hierObject.hierProperties.content.map((item,i)=>{
        let lines=data.filter(item=>item.type==='line'&&item.to===item[idName])
        this.hierObject.hierProperties.content[i].prev=this._getLinesFrom(lines)
      })
    },
    _getLinesFrom(data){
      let list=[];
      data.map(item=>list.push(item.from));
      return list;
    },
    // 调用接口
    addChild(shape, fromId) {
      let newItem = {
        ...this.hierObject.itemTpl(),
        parentId: this.rootData[idName],
        [idName]: shape.id,
        prev: fromId ? [fromId] : [],
        // nodeType: 'leaf',
      }
      this.hierObject.add(newItem);
      return newItem;
    },
    updateChild(newItem) {
      this.hierObject.update(idName, newItem)
    },
    showHier() {
      console.log(JSON.stringify(this.hierObject.hierProperties.content, null, 4))
      console.log(JSON.stringify(this.diagram.data.serialize(), null, 4))
    },
    init(){
      this.editor = new dhx.DiagramEditor(this.$refs.routing, this._getOptions());
      /**编辑器的diagram实例*/
      this.diagram=this.editor.diagram;
      /**初始化界面，去除工具栏、左右面板*/
      this._init_editorPanel();
      /**添加附加图元模板*/
      this._init_template();
      /**绑定diagram事件*/
      this._init_diagram_event();
      /**绑定editor事件*/
      this._init_editor_event();
      /**初始化参数*/
      this._init_param();
    },
    _getOptions(){
      return {
        type: "default",//"default" | "org" | "mindmap"模式中的一种（缺省|组织结构|脑图）
        select:false,//鼠标框选是否有效
        lineConfig: {//连接线配置
          lineType: "line",//"dash" | "line"，虚线|实线
        },
        gridStep: 10,//网格间距
        /**以下default模式有效*/
        autoplacement: {//图元连接方式配置
          mode: "edges",//"direct" | "edges"，edges为在图元边连接点处连接
          graphPadding: 100,//图元间距，缺省为200
        },
        lineGap: 50,//连接线与图元的间距
        /**以上default模式有效*/
        /***********以下配置编辑器*******************************************/
        /**配置 toolbar 的命令按钮是否可以显示*/
        controls: {
          apply: false,
          reset: false,
          export: false,
          import: false,
          autoLayout: false,
          historyManager: false,
          editManager: false,
          scale: true,
          gridStep: false
        },
        editMode: true,//配置是否显示左右面板（左为图例，右为属性）
        shapeToolbar:[//配置选中图元时，图元顶部的工具栏
          {id: "copy", content:'<i class="ivu-icon ivu-icon-md-copy" style="font-size: 20px"></i>',check:shape=>{
            return ['routingRoot', 'workCenter'].includes(shape.type)
          }},
          {id:"remove", content:'<i class="ivu-icon ivu-icon-md-trash" style="font-size: 20px"></i>',check:shape=>{
            return !['routingRoot'].includes(shape.type)
          }},
        ],
        shapeSections: {},
      }
    },
    _getAdditionalTemplate(){
      return {
        routingRoot:{//start的基本配置defaults和样式template
          defaults:{
            shapeType:'routingRoot',
            title:'root',
            width:180,
            height:80,
          },
          template: shape => {
            return (`
                <div class="shape-item root">
                    <div class="shape-item-title">root</div>
                </div>
            `)
          }
        },
        workCenter:{//block的基本配置defaults和样式template
          defaults:{
            shapeType:'workCenter',
            title:'workCenter',
            width:180,
            height:80,
          },
          template: shape => {
            let item = this.hierObject.find(idName, shape.id) || {link: {}}
            return (`
                <div class="shape-item node"
                  style="background-color: ${shape.properties.nodeBgColor}; border-color: ${shape.properties.nodeTitleColor}">
                    <div class="shape-item-title" style="background-color: ${shape.properties.nodeTitleColor}"
                      >${item.name || 'workCenter'}</div>
                    <h4 class="shape-item-desc">
                      ${item.link && item.link.linkClassName ? item.link.linkClassName : '' || ''}
                    </h4>
                </div>
            `)
          }
        }
      }
    },
    _init_param(){
      this.currentShape=null;
      /**初始化数据*/
      this.diagram.data.parse([]);
    },
    /**初始化工具栏、左右面板*/
    _init_editorPanel(){
      this.$nextTick(() => {
        const toolbar = document.querySelector(".dhx_topbar");
        const rightPanel = document.querySelector(".dhx_diagram_editor__sidebar");
        const leftPanel = document.querySelector(".dhx_diagram_editor_shapebar__container");
        toolbar.style.display = "none";
        rightPanel.style.display = "none";
        leftPanel.style.display = "none";
      })
    },
    /**附加图元模板*/
    _init_template(){
      let additionalTemplate=this._getAdditionalTemplate();
      Object.keys(additionalTemplate).map(key=>{
        this.diagram.addShape(key, {
          template: additionalTemplate[key].template,
          defaults: additionalTemplate[key].defaults
        });
      })
    },
    /**绑定editor事件*/
    _init_editor_event(){
      /**设置图元顶部工具栏的事件方法*/
      this.editor.events.on('beforeShapeIconClick',async (iconId,shape) => {
        switch (iconId) {
          case 'info':
            this.showProp(shape.id)
            break;
          case 'remove':
            //  return await dispatch('removeModel',shape);
            return false
            break;
          case 'add':
          case 'copy':
            this.curCopyData = shape
            break;
        }
      });
    },
    /**绑定diagram事件*/
    _init_diagram_event(){
      let _this=this;
      _this.diagram.events.on("itemDblClick", (id, event) => { // itemDblClick
        (id !== this.rootData[idName]) && this.showProp(id)
      });
      _this.diagram.events.on("change", (id, status, shape) => {
        if (!status || !shape || !shape.type) {
          return
        }
        switch(shape.type) {
          case 'line':
            if (!!shape.from && !!shape.to) {
              console.log("🚀 ~ file: RoutingConfig.vue:216 ~ _this.diagram.events.on ~ status,shape:", status,shape)
              if(status==='update') { // &&!shape.added
                _this._addLine(shape)
              }
              if(status==='remove'){
                _this._removeLine(shape);
              }
            }
            break;
          case 'workCenter':
          case 'routingRoot':
              if(status==='add') {
                if (shape.type === 'routingRoot') {
                  shape.shapeType = "workCenter"
                  shape.type = "workCenter"
                }
                _this._addWC(shape)
              }
              if(status==='remove'){
                _this._removeWC(shape)
              }
              break;
          default:
              break;
        }
      });
    },
  },
  watch:{},
  props:{},
  components: {routingModel, routingConfigPanel},
  computed:{
    lang(){
      return {
        'zh-CN':{
          position:'当前工艺路线',
          save:'保存'
        },
        'en-US':{
          position:'current routing',
          save:'save'
        }
      }[this.G_Locale]
    }
  },
}
</script>

<style scoped lang="less">
.routingConfig-wrapper {
  width:100%;
  height:calc(~"100% - 24px");
  /deep/ .shape-item {
      display:flex;
      flex-direction:column;
      justify-content:flex-start;
      align-items:center;
      background:White;
      border:2px solid Grey;
      border-radius: 4px;
      height:100%;
      overflow: hidden;
      &-title {
          width:100%;
          height: 22px;
          background: dimgrey;
          border-bottom:1px solid Grey;
          color:white;
          font-weight: bolder;
      }
      .shape-item-desc {
        flex: 1;
        display: flex;
        justify-content:center;
        align-items:center;
        width: 100%;
        padding: 8px;
      }
      &.node {
        background: rgb(135, 206, 250);
        border: 2px solid rgb(0, 0, 205);
        .shape-item-title {
          background: rgb(25, 25, 112);
        }
      }
  }
}
.routingTablewp {
    position: absolute;
    top: 150px;
    left: 20px;
    right: 0;
    width: 95%;
    max-height: calc(~"100vh - 155px");
    margin: 0;
    box-shadow: 0 3px 6px 2px #dadada;
    background-color: #fff;
    z-index: 10;
    overflow-x: hidden;
    overflow-y: auto;
    /deep/ .cli-content-outline {
      height: auto;
    }
}
.routing-wrapper {
  width:100%;
  height:100%;
}
</style>
